import { degrees, PDFDocument, rgb, StandardFonts } from 'pdf-lib';
/**
 * 浏览器打开新页签预览pdf
 * blob（必选）: pdf文件信息（Blob对象）【Blob】
 * docTitle（可选）: 浏览器打开新页签的title  【String】
 * isAddWatermark（可选，默认为false）: 是否需要添加水印 【Boolean】
 * watermark（必选）：水印信息 【Object: { type: string, text: string, image:{ bytes: ArrayBuffer, imageType: string } }】
 * watermark.type（可选）：类型 可选值：text、image、canvas
 * watermark.text（watermark.type为image时不填，否则必填）：水印文本。注意：如果watermark.type值为text，text取值仅支持拉丁字母中的218个字符。详见：https://www.npmjs.com/package/pdf-lib
 * watermark.image（watermark.type为image时必填，否则不填）：水印图片
 * watermark.image.bytes：图片ArrayBuffer
 * watermark.image.imageType：图片类型。可选值：png、jpg
 * Edit By WFT
 */
export default class PreviewPdf {
  constructor({ blob, docTitle, isAddWatermark = false, watermark: { type = 'text', text = 'WFT', image } }) {
    const _self = this
    if (!blob) {
      return console.error('[PDF Blob Is a required parameter]')
    }
    if (!isAddWatermark) { // 不添加水印
      console.log(blob, "不添加水印")

      _self.preView(blob, docTitle)
    } else {
      let bytes, imageType
      if (type == 'image') {
        if (!image) {
          return console.error('["image" Is a required parameter]')
        }
        bytes = image.bytes
        imageType = image.imageType
      }

      const map = {
        'text': _self.addTextWatermark.bind(_self),
        'image': _self.addImageWatermark.bind(_self),
        'canvas': _self.addCanvasWatermark.bind(_self)
      }
      // _self.runAsync(blob)
      //兼容低版本的谷歌浏览器
      _self.runAsync(blob).then(pdfDoc => {
        console.log(pdfDoc, "流")
        let params
        if (type == 'text') params = { pdfDoc, text, docTitle }
        if (type == 'image') params = { pdfDoc, bytes, imageType, docTitle }
        if (type == 'canvas') params = { pdfDoc, text, docTitle }
        map[type](params)
      });
    }
  }

  // 添加 Text 水印
  async addTextWatermark({ pdfDoc, text, docTitle }) {
    console.log(StandardFonts, 'StandardFonts-->>') // 字体
    const helveticaFont = await pdfDoc.embedFont(StandardFonts.Helvetica)
    const pages = pdfDoc.getPages()
    for (let i = 0; i < pages.length; i++) {
      let page = pages[i]
      let { width, height } = page.getSize()
      for (let i = 0; i < 6; i++) {
        for (let j = 0; j < 6; j++) {
          page.drawText(text, {
            x: j * 100,
            y: height / 5 + i * 100,
            size: 30,
            font: helveticaFont,
            color: rgb(0.95, 0.1, 0.1),
            opacity: 0.2,
            rotate: degrees(-35),
          })
        }
      }
    }
    // 序列化为字节
    const pdfBytes = await pdfDoc.save()
    this.preView(pdfBytes, docTitle)
  }

  // 添加 image 水印
  async addImageWatermark({ pdfDoc, bytes, imageType, docTitle }) {
    // 嵌入JPG图像字节和PNG图像字节
    let image
    const maps = {
      'jpg': pdfDoc.embedJpg.bind(pdfDoc),
      'png': pdfDoc.embedPng.bind(pdfDoc)
    }
    image = await maps[imageType](bytes)
    // 将JPG图像的宽度/高度缩小到原始大小的50%
    const dims = image.scale(0.5)
    const pages = pdfDoc.getPages()
    for (let i = 0; i < pages.length; i++) {
      let page = pages[i]
      let { width, height } = page.getSize()
      for (let i = 0; i < 6; i++) {
        for (let j = 0; j < 6; j++) {
          page.drawImage(image, {
            x: width / 5 - dims.width / 2 + j * 100,
            y: height / 5 - dims.height / 2 + i * 100,
            width: dims.width,
            height: dims.height,
            rotate: degrees(-35)
          })
        }
      }
    }
    // 序列化为字节
    const pdfBytes = await pdfDoc.save()
    this.preView(pdfBytes, docTitle)
  }

  // 添加 canvas 水印
  addCanvasWatermark({ pdfDoc, text, docTitle }) {



    // labels是要显示的水印文字，垂直排列
    let labels = new Array();
    labels.push(text);

    const pages = pdfDoc.getPages()

    const size = pages[0].getSize()


    let pageWidth = size.width
    let pageHeight = size.height


    let canvas = document.createElement('canvas');
    const context = canvas.getContext('2d');

    let canvasWidth = canvas.width = pageWidth;
    let canvasHeight = canvas.height = pageHeight;

    context.font = '20px Arial'; // 设置文字的大小 
    context.fillStyle = 'black';// 设置文字的颜色
    context.textAlign = 'center'; // 设置文本居中对齐  
    context.textBaseline = 'middle'; // 设置文本基线为中间  

    //  // 需要旋转的角度（以度为单位）  
    //   // const angleInDegrees = 45;  
    //   // const angleInRadians = angleInDegrees * (Math.PI / 60);  

    //   // 旋转角度大小
    //   const angleInRadians = Math.PI / 6;
    //   // 在绕画布逆方向旋转30度
    //   context.rotate(-angleInRadians);
    // 需要旋转的角度（以度为单位）  
    // const angleInDegrees = -25;
    // const angleInRadians = angleInDegrees * (Math.PI / 180);



    // 获取文本的最大长度
    let textWidthNum = Math.max(...labels.map(item => context.measureText(item).width));
  


    // 需要旋转的角度（以度为单位）  
    var angleInDegrees = 0;
    var lineHeight = 0; // 行高  
    var lineSpacing = 0; // 行间距  
    var columnSpacing =0; // 列间距  
      console.log(pageHeight,pageWidth,pageHeight<pageWidth,"00")
    if(pageHeight<pageWidth){
       angleInDegrees = -15;  
        lineHeight = 50; // 行高  
        lineSpacing = 50; // 行间距  
        columnSpacing =textWidthNum/2; // 列间距  
    }else{
       angleInDegrees = -30;  
       lineHeight = 50; // 行高  
       lineSpacing = 100; // 行间距  
       columnSpacing =textWidthNum/3; // 列间距  
    }
    const angleInRadians = angleInDegrees * (Math.PI / 180); 


  

    // 计算canvas的中心点  
    const centerX = canvasWidth / 3;
    const centerY = canvasHeight / 3;



    // 文本行 列
    var row = Math.round(pageHeight/(lineHeight+lineSpacing))//4行
    var col = Math.round(pageWidth / (textWidthNum+columnSpacing));//4列

    // console.log(Math.round(pageHeight/(lineHeight+lineSpacing)),"行")
    // 移动到旋转中心并旋转  
    context.translate(centerX, centerY);
    context.rotate(angleInRadians);
    let maxWidth = 0;
    //  如果文本不一样的计算规则： 计算每行文本的宽度和高度
    const metrics = context.measureText(text);
    maxWidth = Math.max(maxWidth, metrics.width);

    const textWidth = maxWidth + columnSpacing * (col - 1);
    const textHeight = lineHeight * row + lineSpacing * (row - 1);

    //console.log(textWidth,textHeight)
    // 计算文本的起始坐标  

    const offsetX = -textWidth / 2;

    const offsetY = textHeight / 2;

    //console.log("canvasWidth=", canvasWidth, "canvasHeight=", canvasHeight, centerX, centerY, "offsetX=" + offsetX, "offsetY=", offsetY)
    // 绘制文本网格  
    context.fillStyle = 'rgba(187, 187, 187, .8)'; // 字体颜色
    for (let i = 0; i < row; i++) {

      for (let j = 0; j < col; j++) {

        const x = offsetX + j * (maxWidth + columnSpacing);

        const y = offsetY - i * (lineHeight + lineSpacing);


        labels.forEach(item => {
          context.fillText(item, x, y);
        })
       // console.log("i=" + x + ",j=" + y)
      }

    }


    // 恢复之前保存的状态  
    context.restore();







    // let lineHeight = 15, fontHeight = 12, positionY, i
    // i = 0, positionY = 0
    // while (positionY <= pageHeight) {
    //   positionY = positionY + lineHeight * 5
    //   i++
    // }
    // canvasWidth += Math.sin(rotateAngle) * (positionY + i * fontHeight) // 给canvas加上画布向左偏移的最大距离
    // canvasHeight = 2 * canvasHeight
    // for (positionY = 0, i = 0; positionY <= canvasHeight; positionY = positionY + lineHeight * 5) {
    //   // 进行画布偏移是为了让画布旋转之后水印能够左对齐;
    //   context.translate(-(Math.sin(rotateAngle) * (positionY + i * fontHeight)), 0);

    //   for (let positionX = 0; positionX < canvasWidth; positionX += 2 * textWidth) {
    //     let spacing = 0;

    //     labels.forEach(item => {
    //       context.fillText("nihwola"+positionX+""+ positionY, positionX, positionY + spacing);
    //       console.log(item,positionX, positionY + spacing)
    //       context.fillStyle = 'rgba(187, 187, 187, .8)'; // 字体颜色
    //       spacing = spacing + lineHeight;
    //     })
    //   }
    //   context.translate(Math.sin(rotateAngle) * (positionY + i * fontHeight), 0);
    //   context.restore();
    //   i++
    // }
    // 图片的base64编码路径
    let dataUrl = canvas.toDataURL('image/png');


    // 使用Xhr请求获取图片Blob
    let xhr = new XMLHttpRequest();
    xhr.open("get", dataUrl, true);
    xhr.responseType = "blob";
    xhr.onload = res => {

      const imgBlob = res.target.response

      //兼容低版本的谷歌浏览器
      this.runAsyncCanvas(pdfDoc, imgBlob, pages).then(async pngImage => {

        for (let i = 0; i < pages.length; i++) {
          pages[i].drawImage(pngImage)
        }

        const pdfBytes = await pdfDoc.save()
        this.preView(pdfBytes, docTitle)
      })

    }
    xhr.send();
  }

  runAsync(blob) {
    var p = new Promise(function (resolve, reject) {
      //做一些异步操作
      // setTimeout(function () {
      // 创建一个 FileReader 对象
      var reader = new FileReader();
      // 将 Blob 对象转换为数组缓冲区
      reader.onloadend = function (event) {
        const existingPdfBytes = event.target.result;
        var pdfDoc = PDFDocument.load(existingPdfBytes)

        resolve(pdfDoc);
      }
      reader.readAsArrayBuffer(blob);
      // }, 1000);
    }).catch((e) => { });

    return p;

  }

  runAsyncCanvas(pdfDoc, imgBlob, pages) {
    var p = new Promise(function (resolve, reject) {
      //做一些异步操作
      // setTimeout(function () {
      // 创建一个 FileReader 对象
      var reader = new FileReader();
      // 将 Blob 对象转换为数组缓冲区
      reader.onload = function (event) {
        const arrayBuffer = event.target.result;
        var pngImage = pdfDoc.embedPng(arrayBuffer)
        resolve(pngImage);
      }
      reader.readAsArrayBuffer(imgBlob);
      // }, 100);
    }).catch((e) => {

    });
    return p;
  }

  // 预览
  preView(stream, docTitle) {
    const URL = window.URL || window.webkitURL;
    const href = URL.createObjectURL(new Blob([stream], { type: 'application/pdf;charset=utf-8' }))

    //  const iframe = window.parent.document.getElementById("iframe")
    //  const toolbar = iframe.contentWindow.document.querySelector(".pdfui-toolbar");
    //  if (toolbar) {
    //    const printButton = toolbar.querySelector(".pdfui-toolbar-button.print");
    //    const downloadButton = toolbar.querySelector(".pdfui-toolbar-button.download");
    //    if (printButton) {
    //      printButton.style.display = "none";
    //    }
    //    if (downloadButton) {
    //      downloadButton.style.display = "none";
    //    }
    //  }
    if (document.querySelector('#dialogPdf1') == null) {
      window.parent.document.getElementById("iframe").src = href+"#toolbar=0&navpanes=0&scrollbar=0";
      window.parent.document.getElementById("iframe").contentWindow.document.title = docTitle;
      // Add custom CSS to hide the print and download buttons
     

    } else {
      var parentElement = document.querySelector('#dialogPdf1 #iframe');
      parentElement.src = href;
    }






    // const wo = window.open(href)
    // //设置新打开的页签 document title
    // let timer = setInterval(() => {
    //   if(wo.closed) {
    //     clearInterval(timer)
    //   } else {
    //     wo.document.title = docTitle
    //   }
    // }, 500)
  }
}